document.addEventListener('DOMContentLoaded', function () {
    // 获取DOM元素
    const excelFileInput = document.getElementById('excel-file');
    const uploadBtn = document.getElementById('upload-btn');
    const startBtn = document.getElementById('start-btn');
    const pauseBtn = document.getElementById('pause-btn');
    const fullscreenBtn = document.getElementById('fullscreen-btn');
    const flashIntervalInput = document.getElementById('flash-interval');
    const displayTimeInput = document.getElementById('display-time');
    const flashcard = document.getElementById('flashcard');
    const wordElement = flashcard.querySelector('.word');
    const meaningElement = flashcard.querySelector('.meaning');
    const imageElement = flashcard.querySelector('.image');
    const wordListElement = document.getElementById('modal-word-list');
    const progressBar = document.getElementById('progress-bar');
    const showWordListBtn = document.getElementById('show-word-list-btn');

    // 模式切换按钮
    const wordModeBtn = document.getElementById('word-mode-btn');
    const imageModeBtn = document.getElementById('image-mode-btn');
    const wordImportArea = document.getElementById('word-import-area');
    const imageImportArea = document.getElementById('image-import-area');
    
    // 图片上传相关
    const imageFilesInput = document.getElementById('image-files');
    const uploadImagesBtn = document.getElementById('upload-images-btn');

    // 全屏模式元素
    const fullscreenMode = document.getElementById('fullscreen-mode');
    const fullscreenWordElement = fullscreenMode.querySelector('.fullscreen-word');
    const fullscreenMeaningElement = fullscreenMode.querySelector('.fullscreen-meaning');
    const fullscreenImageElement = fullscreenMode.querySelector('.fullscreen-image');
    const fullscreenProgressBar = document.getElementById('fullscreen-progress-bar');
    const startFullscreenBtn = document.getElementById('fullscreen-start-btn');
    const stopFullscreenBtn = document.getElementById('fullscreen-stop-btn');
    const exitFullscreenBtn = document.getElementById('exit-fullscreen-btn');

    // 存储单词数据
    let wordList = [];
    let imageList = [];
    let currentIndex = 0;
    let isPlaying = false;
    let currentMode = 'word'; // 默认为单词模式

    // 模式切换
    wordModeBtn.addEventListener('click', function() {
        setMode('word');
    });

    imageModeBtn.addEventListener('click', function() {
        setMode('image');
    });

    function setMode(mode) {
        currentMode = mode;
        
        // 更新按钮状态
        if (mode === 'word') {
            wordModeBtn.classList.add('active');
            imageModeBtn.classList.remove('active');
            wordImportArea.style.display = 'block';
            imageImportArea.style.display = 'none';
            showWordListBtn.style.display = 'inline-block';
            showImageListBtn.style.display = 'none';
        } else {
            wordModeBtn.classList.remove('active');
            imageModeBtn.classList.add('active');
            wordImportArea.style.display = 'none';
            imageImportArea.style.display = 'block';
            showWordListBtn.style.display = 'none';
            showImageListBtn.style.display = imageList.length > 0 ? 'inline-block' : 'none';
            showImageListBtn.disabled = imageList.length === 0;
        }

        // 重置状态
        isPlaying = false;
        startBtn.disabled = (mode === 'word' && wordList.length === 0) || (mode === 'image' && imageList.length === 0);
        pauseBtn.disabled = true;
        fullscreenBtn.disabled = startBtn.disabled;
        startFullscreenBtn.disabled = startBtn.disabled;
        stopFullscreenBtn.disabled = true;
        currentIndex = 0;
        clearTimeout(diaplayIntervalId);
        clearTimeout(flashIntervalId);
        clearCountdown();
        resetProgressBars();
        // 显示当前模式的内容
        updateDisplay();
    }

    // 上传Excel文件
    uploadBtn.addEventListener('click', function () {
        const file = excelFileInput.files[0];
        if (!file) {
            alert('请选择Excel文件');
            return;
        }

        // 确保XLSX库已加载
        if (typeof XLSX === 'undefined') {
            alert('Excel解析库尚未加载完成，请稍后再试');
            return;
        }

        const reader = new FileReader();
        reader.onload = function (e) {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });

                // 获取第一个工作表
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];

                // 将工作表转换为JSON
                const jsonData = XLSX.utils.sheet_to_json(worksheet);

                // 处理数据
                processWordData(jsonData);
            } catch (error) {
                console.error('解析Excel文件出错:', error);
                alert('解析Excel文件出错，请确保文件格式正确');
            }
        };

        reader.readAsArrayBuffer(file);
    });

    // 处理Excel数据
    function processWordData(data) {
        wordList = [];

        // 尝试不同的可能的列名
        data.forEach(row => {
            let word = '';
            let meaning = '';

            // 尝试不同的可能的列名组合
            if (row['单词'] && row['释义']) {
                word = row['单词'];
                meaning = row['释义'];
            } else if (row['word'] && row['meaning']) {
                word = row['word'];
                meaning = row['meaning'];
            } else if (row['英文'] && row['中文']) {
                word = row['英文'];
                meaning = row['中文'];
            } else if (row['Word'] && row['Meaning']) {
                word = row['Word'];
                meaning = row['Meaning'];
            } else {
                // 如果没有匹配的列名，尝试使用第一列和第二列
                const keys = Object.keys(row);
                if (keys.length >= 2) {
                    word = row[keys[0]];
                    meaning = row[keys[1]];
                }
            }

            if (word && meaning) {
                wordList.push({ word, meaning });
            }
        });

        // 显示单词列表
        displayWordList();

        // 启用开始按钮和全屏按钮
        if (wordList.length > 0) {
            startBtn.disabled = false;
            startFullscreenBtn.disabled = false;
            fullscreenBtn.disabled = false;
            showWordListBtn.disabled = false;
            currentIndex = 0
            clearTimeout(diaplayIntervalId); // 清除之前的定时器
            clearTimeout(flashIntervalId); // 清除之前的定时器
            clearCountdown(); // 清除之前的倒计时
            resetProgressBars(); // 重置进度条
            showWord(currentIndex); // 显示当前单词
        } else {
            alert('未找到有效的单词数据，请检查Excel文件格式');
        }
    }

    // 图片上传处理
    // 修改图片上传处理函数，隐藏图片预览容器
    uploadImagesBtn.addEventListener('click', function() {
        const files = imageFilesInput.files;
        if (files.length === 0) {
            alert('请选择图片文件');
            return;
        }
    
        // 清空之前的图片列表
        imageList = [];
 
    
        // 处理每个图片文件
        Array.from(files).forEach((file, index) => {
            if (!file.type.startsWith('image/')) {
                console.warn(`文件 ${file.name} 不是图片，已跳过`);
                return;
            }
    
            const reader = new FileReader();
            reader.onload = function(e) {
                // 创建图片对象
                const imageObj = {
                    src: e.target.result,
                    name: file.name
                };
                imageList.push(imageObj);
    
                // 如果是第一张图片，启用按钮
                if (imageList.length === 1) {
                    startBtn.disabled = false;
                    startFullscreenBtn.disabled = false;
                    fullscreenBtn.disabled = false;
                    showImageListBtn.disabled = false;
                    showImageListBtn.style.display = 'inline-block';
                    currentIndex = 0;
                    clearTimeout(diaplayIntervalId);
                    clearTimeout(flashIntervalId);
                    clearCountdown();
                    resetProgressBars();
                    showImage(currentIndex);
                }
                
                // 更新图片列表显示
                displayImageList();
            };
            reader.readAsDataURL(file);
        });
    });
    
    // 修改图片列表显示函数，添加点击查看图片功能
    function displayImageList() {
        const imageListElement = document.getElementById('modal-image-list');
        imageListElement.innerHTML = '';
    
        imageList.forEach((item, index) => {
            const imageItem = document.createElement('div');
            imageItem.className = 'image-item';
            
            const imgElement = document.createElement('img');
            imgElement.src = item.src;
            imgElement.alt = item.name;
            imgElement.className = 'image-thumbnail';
            
            const nameElement = document.createElement('div');
            nameElement.className = 'image-name';
            nameElement.textContent = item.name;
            
            // 添加点击事件，显示大图
            imageItem.addEventListener('click', function() {
                currentIndex = index;
                showImage(currentIndex);
                closeImageListModal();
            });
            
            imageItem.appendChild(imgElement);
            imageItem.appendChild(nameElement);
            imageListElement.appendChild(imageItem);
        });
    }

    // 显示单词列表
    function displayWordList() {
        wordListElement.innerHTML = '';

        wordList.forEach((item, index) => {
            const wordItem = document.createElement('div');
            wordItem.className = 'word-item';
            wordItem.innerHTML = `
                <span class="word-english">${item.word}</span>
                <span class="word-chinese">${item.meaning}</span>
            `;
            wordListElement.appendChild(wordItem);
        });
    }

    // 全屏按钮点击事件
    fullscreenBtn.addEventListener('click', function () {
        if ((currentMode === 'word' && wordList.length === 0) || 
            (currentMode === 'image' && imageList.length === 0)) {
            alert('请先导入内容');
            return;
        }
        enterFullscreenMode();
    });

    // 进入全屏模式
    function enterFullscreenMode() {
        fullscreenMode.classList.add('active');
        document.body.style.overflow = 'hidden'; // 防止滚动
    }

    // 退出全屏模式
    function exitFullscreenMode() {
        fullscreenMode.classList.remove('active');
        document.body.style.overflow = ''; // 恢复滚动
    }

    // 退出全屏按钮点击事件
    exitFullscreenBtn.addEventListener('click', function () {
        exitFullscreenMode();
        if (isPlaying) {
            pauseBtn.click(); // 暂停播放
        }
    });

    // 开始按钮点击事件
    startBtn.addEventListener('click', startClickEvent);
    startFullscreenBtn.addEventListener('click', startClickEvent);

    function startClickEvent() {
        if ((currentMode === 'word' && wordList.length === 0) || 
            (currentMode === 'image' && imageList.length === 0)) {
            alert('请先导入内容');
            return;
        }
        isPlaying = true;
        startBtn.disabled = true;
        startFullscreenBtn.disabled = true;
        pauseBtn.disabled = false;
        stopFullscreenBtn.disabled = false;
        // 开始循环显示内容
        startFlashcards();
    }

    // 暂停按钮点击事件
    pauseBtn.addEventListener('click', stopClickEvent);
    stopFullscreenBtn.addEventListener('click', stopClickEvent);

    function stopClickEvent() {
        isPlaying = false;
        startBtn.disabled = false;
        startFullscreenBtn.disabled = false;
        pauseBtn.disabled = true;
        stopFullscreenBtn.disabled = true;

        clearTimeout(diaplayIntervalId); // 清除之前的定时器
        clearTimeout(flashIntervalId); // 清除之前的定时器
        clearCountdown(); // 清除之前的倒计时
        resetProgressBars(); // 重置进度条
        updateDisplay(); // 显示当前内容
    }

    // 重置所有进度条
    function resetProgressBars() {
        progressBar.style.width = '0%';
        fullscreenProgressBar.style.width = '0%';
    }

    let diaplayIntervalId; // 定义定时器 ID 以便控制清除
    let flashIntervalId; // 定义定时器 ID 以便控制清除
    let countdownIntervalId; // 定义定时器 ID 以便控制清除

    // 启动闪卡循环
    function startFlashcards() {
        const flashInterval = parseFloat(flashIntervalInput.value) * 1000; // 获取闪现间隔（秒转毫秒）
        const displayTime = parseFloat(displayTimeInput.value) * 1000; // 获取显示时间（秒转毫秒）

        clearTimeout(diaplayIntervalId); // 清除之前的定时器
        clearTimeout(flashIntervalId); // 清除之前的定时器
        clearCountdown(); // 清除之前的倒计时
        resetProgressBars(); // 重置进度条
        updateDisplay(); // 显示当前内容

        // 开始闪卡循环
        function flashcardCycle() {
            if (!isPlaying) return; // 如果不是播放状态，停止循环

            updateProgressBars(displayTime); // 更新进度条
            diaplayIntervalId = setTimeout(() => {
                if (!isPlaying) return;

                resetProgressBars(); // 重置进度条
                hideContent(); // 隐藏当前内容

                // 设置空白时间间隔
                flashIntervalId = setTimeout(() => {
                    if (!isPlaying) return;

                    // 更新索引，根据当前模式选择正确的列表长度
                    const listLength = currentMode === 'word' ? wordList.length : imageList.length;
                    currentIndex = (currentIndex + 1) % listLength;
                    updateDisplay(); // 显示下一个内容
                    flashcardCycle(); // 继续下一个循环
                }, flashInterval);
            }, displayTime); // 设置显示时间
        }

        flashcardCycle(); // 启动首次循环
    }

    // 更新进度条的状态
    function updateProgressBars(duration) {
        const startTime = Date.now();
        const endTime = startTime + duration;

        // 更新进度条的函数
        function updateProgress() {
            if (!isPlaying) return; // 如果不是播放状态，停止更新

            const now = Date.now();
            const elapsed = now - startTime;
            const percent = Math.min((elapsed / duration) * 100, 100); // 计算进度百分比

            // 更新进度条宽度
            progressBar.style.width = `${percent}%`;
            fullscreenProgressBar.style.width = `${percent}%`;

            // 如果显示时间未结束，继续更新进度
            if (now < endTime) {
                requestAnimationFrame(updateProgress);
            }
        }

        // 启动进度条更新
        requestAnimationFrame(updateProgress);
    }

    function resetProgressBars() {
        progressBar.style.width = '0%';
        fullscreenProgressBar.style.width = '0%';

        // 强制刷新浏览器渲染
        requestAnimationFrame(() => {
            progressBar.style.width = '0%';
            fullscreenProgressBar.style.width = '0%';
        });
    }

    // 隐藏内容的函数
    function hideContent() {
        // 隐藏卡片和进度条
        document.querySelector('.flashcard').style.display = 'none';
        document.querySelector('.progress-container').style.display = 'none';
        document.querySelector('.fullscreen-flashcard').style.display = 'none';
        document.querySelector('.fullscreen-progress-container').style.display = 'none';

        // 创建倒计时元素
        const countdown = document.createElement('div');
        countdown.className = 'countdown';
        countdown.textContent = flashIntervalInput.value;
        document.querySelector('.flashcard-container').appendChild(countdown);

        const fullscreenCountdown = document.createElement('div');
        fullscreenCountdown.className = 'fullscreen-countdown';
        fullscreenCountdown.textContent = flashIntervalInput.value;
        document.querySelector('.fullscreen-flashcard-container').appendChild(fullscreenCountdown);

        // 开始倒计时
        let count = parseInt(flashIntervalInput.value);
        countdownIntervalId = setInterval(() => {
            count--;
            if (count > 0) {
                countdown.textContent = count;
                fullscreenCountdown.textContent = count;
            } else {
                clearInterval(countdownIntervalId);
                countdown.remove();
                fullscreenCountdown.remove();
            }
        }, 1000);
    }

    function clearCountdown() {
        const countdown = document.querySelector('.countdown');
        if (countdown) {
            countdown.remove();
        }
        const fullscreenCountdown = document.querySelector('.fullscreen-countdown');
        if (fullscreenCountdown) {
            fullscreenCountdown.remove();
        }
        clearInterval(countdownIntervalId);
    }

    // 更新显示内容（根据当前模式）
    function updateDisplay() {
        if (currentMode === 'word') {
            showWord(currentIndex);
        } else {
            showImage(currentIndex);
        }
    }

    // 显示单词
    function showWord(index) {
        // 显示卡片和进度条
        document.querySelector('.flashcard').style.display = 'flex';
        document.querySelector('.progress-container').style.display = 'block';
        document.querySelector('.fullscreen-flashcard').style.display = 'flex';
        document.querySelector('.fullscreen-progress-container').style.display = 'block';

        // 显示单词，隐藏图片
        wordElement.style.display = 'block';
        meaningElement.style.display = 'block';
        imageElement.style.display = 'none';
        imageElement.innerHTML = '';
        
        fullscreenWordElement.style.display = 'block';
        fullscreenMeaningElement.style.display = 'block';
        fullscreenImageElement.style.display = 'none';
        fullscreenImageElement.innerHTML = '';

        // 设置单词内容
        wordElement.textContent = wordList[index].word;
        meaningElement.textContent = wordList[index].meaning;
        fullscreenWordElement.textContent = wordList[index].word;
        fullscreenMeaningElement.textContent = wordList[index].meaning;
    }

    // 显示图片
    function showImage(index) {
        // 显示卡片和进度条
        document.querySelector('.flashcard').style.display = 'flex';
        document.querySelector('.progress-container').style.display = 'block';
        document.querySelector('.fullscreen-flashcard').style.display = 'flex';
        document.querySelector('.fullscreen-progress-container').style.display = 'block';

        // 隐藏单词，显示图片
        wordElement.style.display = 'none';
        meaningElement.style.display = 'none';
        imageElement.style.display = 'flex';
        
        fullscreenWordElement.style.display = 'none';
        fullscreenMeaningElement.style.display = 'none';
        fullscreenImageElement.style.display = 'flex';

        // 设置图片内容
        imageElement.innerHTML = `<img src="${imageList[index].src}" alt="${imageList[index].name}">`;
        fullscreenImageElement.innerHTML = `<img src="${imageList[index].src}" alt="${imageList[index].name}">`;
    }

    // 键盘事件监听（按ESC键退出全屏）
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && fullscreenMode.classList.contains('active')) {
            exitFullscreenMode();
            if (isPlaying) {
                pauseBtn.click(); // 暂停播放
            }
        }
    });
});


// 图片模式下的查看图片列表按钮
const showImageListBtn = document.createElement('button');
showImageListBtn.id = 'show-image-list-btn';
showImageListBtn.textContent = '查看图片列表';
showImageListBtn.onclick = function() { showImageListModal(); };
showImageListBtn.disabled = true;
showImageListBtn.style.display = 'none';
document.querySelector('.control-buttons').appendChild(showImageListBtn);

// 显示图片列表模态框
function showImageListModal() {
    const modal = document.getElementById('image-list-modal');
    modal.style.display = 'block';
}

// 关闭图片列表模态框
function closeImageListModal() {
    document.getElementById('image-list-modal').style.display = 'none';
}

// 显示图片列表
function displayImageList() {
    const imageListElement = document.getElementById('modal-image-list');
    imageListElement.innerHTML = '';

    imageList.forEach((item, index) => {
        const imageItem = document.createElement('div');
        imageItem.className = 'image-item';
        
        const imgElement = document.createElement('img');
        imgElement.src = item.src;
        imgElement.alt = item.name;
        imgElement.className = 'image-thumbnail';
        
        const nameElement = document.createElement('div');
        nameElement.className = 'image-name';
        nameElement.textContent = item.name;
        
        imageItem.appendChild(imgElement);
        imageItem.appendChild(nameElement);
        imageListElement.appendChild(imageItem);
    });
}

function showWordListModal() {
    const modal = document.getElementById('word-list-modal');
    modal.style.display = 'block';
}

function closeWordListModal() {
    document.getElementById('word-list-modal').style.display = 'none';
}

// 在文件上传处理完成后调用
function handleFileUploadComplete() {
    document.getElementById('show-word-list-btn').style.display = 'block';
}